package com.meirengu.utils.crypto;


import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

/**
 * ClassName: CryptAES(AES加密类 可与PHP对应)
 *
 * @Version 1.0
 * @Author: airufei
 * date: 2016年10月31日 上午10:02:19
 */
public class HCCryptAES {

    private static final String AESTYPE = "AES/ECB/PKCS5Padding";
    private static Logger logger = LoggerFactory.getLogger(HCCryptAES.class);

    /**
     * AES_Encrypt:(加密)
     *
     * @param keyStr
     * @param plainText
     * @return
     * @Author airufei
     */
    public static String AES_Encrypt(String keyStr, String plainText) {

        byte[] encrypt = null;

        try {

            Key key = generateKey(keyStr);

            Cipher cipher = Cipher.getInstance(AESTYPE);

            cipher.init(Cipher.ENCRYPT_MODE, key);

            encrypt = cipher.doFinal(plainText.getBytes());

        } catch (Exception e) {
            logger.error("AES_Encrypt:(加密)失败======>:" + e.getMessage());
        }

        return new String(Base64.encodeBase64(encrypt));

    }

    /**
     * AES_Decrypt:(解密)
     *
     * @param keyStr
     * @param encryptData
     * @return
     * @Author airufei
     */
    public static String AES_Decrypt(String keyStr, String encryptData) {
        byte[] decrypt = null;
        try {

            Key key = generateKey(keyStr);

            Cipher cipher = Cipher.getInstance(AESTYPE);

            cipher.init(Cipher.DECRYPT_MODE, key);

            decrypt = cipher.doFinal(Base64.decodeBase64(encryptData));

        } catch (Exception e) {
            logger.error(" AES_Decrypt:(解密)失败======>:" + e.getMessage());
        }

        return new String(decrypt).trim();

    }

    private static Key generateKey(String key) throws Exception {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            return keySpec;
        } catch (Exception e) {
            logger.error(" generateKey:(获取key)失败======>:" + e.getMessage());
            throw e;

        }

    }

}

